export const addNavBar = (editor) => {
  const opts = {
    id: "navbar",
    label: "Navbar",
    classPrefix: "navbar",
    style: "",
    styleAdditional: "",
  };

  const { Components,BlockManager } = editor;
  const { id, label } = opts;

  const navbarPfx = opts.classPrefix;
  const idContainer = `${id}-container`;
  const idNavMenu = `${id}-nav-menu`;
  const idNavMenuLink = `${id}-nav-menu-link`;
  const idBurgerMenu = `${id}-burger-menu`;
  const idBurgerMenuLine = `${id}-burger-menu-line`;
  const idBurgerMenuButton = `${id}-burger-menu-button`;
  const idBurgerMenuSearch = `${id}-burger-menu-search`;

  // 这个组件是通过 https://github.com/GrapesJS/components-navbar 这里简单修改的
  // 点击"首页"，再点击右边的组件栏左边的小齿轮，可以输入跳转的url，但是点击"首页"进行跳转需要导出代码才会跳转
  // 在缩小宽度到768px时，会自适应，出现展开图标，点击则展开导航项
  // 双击logo可以更换图片
  // idContainer中左边是一个默认的link，中间是idBurgerMenu，右边是idNavMenu，含有三个idNavMenuLink。
  // idNavMenu中有三个idNavMenuLink
  // idBurgerMenu中有idBurgerMenuLine，idBurgerMenuLine是一个css写的展开图标，也就是当缩小到一定宽度时，就会使用idBurgerMenu
  Components.addType(id, {
    model: {
      defaults: {
        name: label,
        attributes: { class: navbarPfx ,'data-gjs-type':id},
        components: { type: idContainer },
        styles:
          (opts.style ||
            `
          .${navbarPfx} {
            background-color: #fff;
            color: #000;
            min-height: 50px;
            width: 100%;
            border-bottom:2.5px solid #e9e9e9;
          }

          .${navbarPfx}-container {
            // max-width: 1200px;
            margin: 0 auto;
          }

          .${navbarPfx}-items-c {
            display: inline-block;
            float: right;
          }

          .${navbarPfx}-container::after {
            content: "";
            clear: both;
            display: block;
          }

          .${navbarPfx}-logo {
            vertical-align: top;
            display: inline-block;
            padding: 10px 5px 1px 5px;
            min-height: 50px; 
            min-width: 50px;  
            max-height: 150px; 
            max-width: 150px;  
            object-fit: contain; /* 确保图像保持纵横比 */
            color: inherit;
            text-decoration: none;
          }

          .${navbarPfx}-menu {
            padding: 10px 0;
            display: block;
            float: left;
            margin: 0;
            display: flex;
          }

          .${navbarPfx}-menu-link {
            margin: 0;
            color: inherit;
            text-decoration: none;
            display: inline-block;
            padding: 10px 15px;
          }

          .${navbarPfx}-burger {
            margin: 10px 0;
            width: 45px;
            padding: 5px 10px;
            display: none;
            float: right;
            cursor: pointer;
          }

          .${navbarPfx}-burger-line {
            padding: 1px;
            background-color: black;
            margin: 5px 0;
          }
          
          .${navbarPfx}-burger-button {
            min-height: 62px;
            float: right;
            background-color: #02a7f0;
            color: white;
            border: none;
            padding-left: 20px;
            padding-right: 20px;
            align-content: center;
          }

          @media (max-width: 768px) {
            .${navbarPfx}-items-c {
              display: none;
              width: 100%;
              text-align: center;
            }
            .${navbarPfx}-items-c:hover{
              overflow: hidden;
            }
            .${navbarPfx}-burger {
              display: block;
              text-align: center;
            }
            .${navbarPfx}-menu {
              width: 100%;
              text-align: center;
            }
            .${navbarPfx}-menu-link {
              display: block;
              text-align: center;
            }
            .${navbarPfx}-menu-link:hover {
              transform: scale(1.1);
              background: #f0f0f0;
              overflow-x: hidden;
            }
            .${navbarPfx}-burger-button{
              width: 100%;
              text-align: center;
            }
          }
        `) + opts.styleAdditional,
      },
    },
  });

  Components.addType(idContainer, {
    model: {
      defaults: {
        attributes: { class: `${navbarPfx}-container`, "data-gjs": "navbar",'data-gjs-type':idContainer },
        name: "Navbar Container",
        components: [
          {
            type: "image",
            attributes: {
              class: `${navbarPfx}-logo`,
              src: "https://cdn4.codesign.qq.com/prototypes/2023/08/03/xDP3923q32qn08ZwlKp03/apgsmrtqzvfi3x3v/f754607f7d30679d5424a2624d2802b0.png",
              alt: "Brand",
            },
          },
          { type: idBurgerMenu },
          {
            attributes: {
              class: `${navbarPfx}-items-c`,
              "data-gjs": "navbar-items",
            },
            components: [
              { type: idNavMenu },
              { type: idBurgerMenuButton },
            ],
          },
        ],
      },
    },
  });

  Components.addType(idNavMenu, {
    model: {
      defaults: {
        name: "Navbar Menu",
        tagName: "nav",
        attributes: { class: `${navbarPfx}-menu`, "data-gjs": "navbar-menu" ,'data-gjs-type':idNavMenu},
        components: [
          { type: idNavMenuLink, components: "首页" },
          { type: idNavMenuLink, components: "产品中心" },
          { type: idNavMenuLink, components: "其他" },
          { type: idBurgerMenuSearch },
        ],
      },
    },
  });

  Components.addType(idNavMenuLink, {
    extend: "link",
    model: {
      defaults: {
        name: "Menu link",
        draggable: `[data-gjs-type="${idNavMenu}"]`,
        attributes: { class: `${navbarPfx}-menu-link`, "data-gjs": "navbar-menu-link" ,'data-gjs-type':idNavMenuLink},
      },
    },
  });

  Components.addType(idBurgerMenu, {
    model: {
      defaults: {
        name: "Burger",
        draggable: false,
        copyable: false,
        removable: false,
        script: function () {
          // @ts-ignore
          const currentEl = this;
          const stringCollapse = "gjs-collapse";
          const clickEvent = "click";
          const transitProp = "max-height";
          let transEndAdded;
          let isAnimating = 0;

          const getTransitionEvent = function () {
            const el = document.createElement("void");
            const transitions = {
              transition: "transitionend",
              OTransition: "oTransitionEnd",
              MozTransition: "transitionend",
              WebkitTransition: "webkitTransitionEnd",
            };

            for (let t in transitions) {
              // @ts-ignore
              if (el.style[t] !== undefined) {
                return transitions[t];
              }
            }
          };

          const transitEndEvent = getTransitionEvent();

          var getElHeight = function (el) {
            const style = window.getComputedStyle(el);
            const elDisplay = style.display;
            // @ts-ignore
            const elMaxHeight = parseInt(style[transitProp]);

            if (elDisplay !== "none" && elMaxHeight !== 0) {
              return el.offsetHeight;
            }

            el.style.height = "auto";
            el.style.display = "block";
            el.style.position = "absolute";
            el.style.visibility = "hidden";
            const height = el.offsetHeight;
            el.style.height = "";
            el.style.display = "";
            el.style.position = "";
            el.style.visibility = "";

            return height;
          };

          var toggleSlide = function (el) {
            isAnimating = 1;
            var elMaxHeight = getElHeight(el);
            var elStyle = el.style;
            elStyle.display = "block";
            elStyle.transition = `${transitProp} 0.25s ease-in-out`;
            elStyle.overflowY = "hidden";

            if (elStyle[transitProp] == "") {
              elStyle[transitProp] = 0;
            }

            if (parseInt(elStyle[transitProp]) == 0) {
              elStyle[transitProp] = "0";
              setTimeout(function () {
                elStyle[transitProp] = elMaxHeight + "px";
              }, 10);
            } else {
              elStyle[transitProp] = "0";
            }
          };

          const toggle = function (ev) {
            ev.preventDefault();
            if (isAnimating) return;

            const navParent = currentEl.closest("[data-gjs=navbar]");
            const navItems = navParent.querySelector("[data-gjs=navbar-items]");
            navItems && toggleSlide(navItems);

            if (!transEndAdded) {
              navItems.addEventListener(transitEndEvent, function () {
                isAnimating = 0;
                const itemsStyle = navItems.style;
                if (parseInt(itemsStyle[transitProp]) == 0) {
                  itemsStyle.display = "";
                  itemsStyle[transitProp] = "";
                }
              });
              transEndAdded = 1;
            }
          };

          if (!(stringCollapse in currentEl)) {
            currentEl.addEventListener(clickEvent, toggle);
          }

          // @ts-ignore
          currentEl[stringCollapse] = 1;
        },
        attributes: { class: `${navbarPfx}-burger` ,'data-gjs-type':idBurgerMenu},
        components: [
          { type: idBurgerMenuLine },
          { type: idBurgerMenuLine },
          { type: idBurgerMenuLine },
        ],
      },
    },
  });

  Components.addType(idBurgerMenuLine, {
    model: {
      defaults: {
        name: "Burger Line",
        draggable: false,
        highlightable: false,
        attributes: { class: `${navbarPfx}-burger-line` ,'data-gjs-type':idBurgerMenuLine},
      },
    },
  });

  Components.addType(idBurgerMenuButton, {
    model: {
      defaults: {
        name: "Burger Button",
        draggable: false,
        highlightable: false,
        attributes: { class: `${navbarPfx}-burger-button` ,'data-gjs-type':idBurgerMenuButton},
        components: [{ type: "link", content: "登录/注册" }],
      },
    },
  });

  // 添加一个搜索框
  Components.addType(idBurgerMenuSearch, {
    model: {
      defaults: {
        name: "Burger Search",
        draggable: false,
        highlightable: false,
        attributes: { "data-gjs": "navbar-menu-search" ,'data-gjs-type':idBurgerMenuSearch},
        components: {
          type: "searchs",
          content: `
          <div class="searchs-outer" style="margin-right:10px;">
            <div class="searchs-input" style="width: 80%;height: 40px;display: flex;background-color: white;border: 1px solid lightgray;align-items: center;justify-content: space-between;transition: 1s;" tabindex="1">              
              <img class="searchs-img" src="https://ts1.cn.mm.bing.net/th/id/R-C.bf5e6bcabaaa8143e41ce10c63d5bd79?rik=fEgSv7W2WL%2bhbg&riu=http%3a%2f%2ficon.chrafz.com%2fuploads%2fallimg%2f170119%2f1-1F1191335510-L.png&ehk=UGOqdbbRrVRodnBwCyG7i7dgq3%2b2pmT6OpqYL3u%2bjBA%3d&risl=&pid=ImgRaw&r=0" />              
              <input type="text" placeholder="请输入搜索关键字" class="searchs-input-focus" />              
            </div>              
            <div class="searchs-history" style="width: 100%;transition: 1s;display: none;padding: 10px 20px 20px 0;">                  
              <div class="searchs-history-tip" style=" display: flex;justify-content: space-between;font-size: 18px;width: 100%;color:black;">                  
                <div>搜索历史
                </div>
                <div class="searchs-clear" style="font-size: 12px;">清除
                </div>
              </div>                  
              <div class="searchs-history-content" style="margin-top: 3%;width: 100%;height: 80%;display: flex;">                      
                <div style="width:30%;margin-right:3%;">test1</div>                      
                <div style="width:30%;margin-right:3%;">test2</div>                  
              </div>              
            </div>
          </div>`,
        },
      },
    },
  });

  Components.addType('searchs', {
    model: {
      defaults: {
        script() {
          const that = this
          // 元素监听-搜索框获取焦点事件
          var th = document.getElementById(this.attributes.id.value);
          var navbarMenuLink = document.querySelectorAll("[data-gjs='navbar-menu-link']");
          var navbarMenuSearch = document.querySelector("[data-gjs='navbar-menu-search']");
          console.log(this.attributes)
          console.log('---------------------------------------------------------')
          console.log('this.attributes.id.value:' + this.attributes.id.value)
          th.getElementsByClassName('searchs-input-focus')[0].onfocus = function () {
            var ch = th.getElementsByClassName("searchs-input")[0]
            var searchInput = th.getElementsByClassName("searchs-input-focus")[0]
            var searchHistory = th.getElementsByClassName("searchs-history")[0]
            searchInput.style.width = '80%'
            ch.style.width = '100%'
            ch.style.borderRadius = "20px";
            searchInput.style.borderRadius = "20px";
            ch.style.flexDirection = 'row-reverse';
            searchHistory.style.width = '560px';
            searchHistory.style.height = '100px';
            searchHistory.style.backgroundColor = 'white';
            searchHistory.style.boder = '1px solid lightgray';
            searchHistory.style.display = 'inherit';
            searchHistory.style.position = 'absolute';

            for (var i = 0; i < navbarMenuLink.length; i++) {
              navbarMenuLink[i].style.display = "none";
            }
            if(navbarMenuSearch.style){
              navbarMenuSearch.style.width = '560px';
            }
          }
          // 搜索框失去焦点事件
          th.getElementsByClassName('searchs-outer')[0].onmouseleave = function () {
            var ch = th.getElementsByClassName("searchs-input")[0]
            var searchInput = th.getElementsByClassName("searchs-input-focus")[0]
            var searchHistory = th.getElementsByClassName("searchs-history")[0]
            searchInput.style.width = '95%'
            ch.style.width = '80%'
            ch.style.borderRadius = "0px";
            searchInput.style.borderRadius = "0px";
            ch.style.flexDirection = 'row';
            searchHistory.style.display = 'none';

            for (var i = 0; i < navbarMenuLink.length; i++) {
              navbarMenuLink[i].style.display = "block";
            }
            console.log('111')
            if(navbarMenuSearch.style){
              navbarMenuSearch.style.width = 'auto';
            }
          }

          th.getElementsByClassName('searchs-img')[0].onclick = function () {
            var searchInput = th.getElementsByClassName("searchs-input-focus")[0]
            if (!searchInput.value) alert("请输入搜索内容！")
            else {
              alert('搜索内容为' + searchInput.value)
              var inner = th.getElementsByClassName('searchs-history-content')[0];
              var test = document.createElement('div');
              test.innerText = searchInput.value;
              inner.appendChild(test);
            }
          };
          th.getElementsByClassName('searchs-clear')[0].onclick = function () {
            var r = confirm("是否确认清空搜索历史!");
            if (r == true) {
              var inner = th.getElementsByClassName('searchs-history-content')[0];
              inner.innerHTML = ''
            }
          };
          var searchInput = th.getElementsByClassName("searchs-input-focus")[0]
          var searchItem = th.getElementsByClassName('searchs-history-content')[0].getElementsByTagName("div");
          for (var i = 0; i < searchItem.length; i++) {
            // 对每个div元素进行操作，例如：  
            searchItem[i].onclick = function () {
              searchInput.value = this.textContent
            }
          }
        },
        styles:
          '.searchs-history{\
              width: 52%;\
              transition: 1s;\
              display: none;\
              padding: 20px;\
          }\
          .searchs-history-tip{\
              display: flex;\
              justify-content: space-between;\
              font-size: 18px;\
              width: 100%;\
              color:black;\
          }\
          .searchs-history-content{\
              margin-top: 1%;\
              width: 100%;\
              height: 80%;\
              display: flex;\
          }\
          .searchs-history-content>div{\
              margin-right:1%;\
              font-size: 13px;\
              color: rgb(153, 153, 153);\
              display: flex;\
              align-items: center;\
              justify-content: center;\
              width: 8%;\
              height: 50%;\
              background-color: #f4f4f5;\
              border: 1px solid #dedfe0;\
              border-radius: 5px;\
          }\
          .searchs-history-content>div:hover{\
              color: black;\
          }\
          .searchs-input {\
              width: 50%;\
              height: 40px;\
              display: flex;\
              background-color: white;\
              border: 1px solid lightgray;\
              align-items: center;\
              justify-content: space-between;\
              transition: 1s;\
          }\
          .searchs-input>img {\
              margin-left: 10px;\
              margin-right: 10px;\
              width: 30px;\
              height: 30px;\
              transition: 1s;\
          }\
          .searchs-input>input {\
              height: 95%;\
              width:95%;\
              border: none;\
              outline: none;\
              margin-left: 5px;\
              margin-right: 5px;\
              transition: 1.5s;\
          }'
      }
    }
  });
  BlockManager.add("navbar", {
    // 分类的展示图标
    media: `<svg viewBox="0 0 24 24" style="width:30px; height:30px">
            <path d="M22 9c0-.6-.5-1-1.25-1H3.25C2.5 8 2 8.4 2 9v6c0 .6.5 1 1.25 1h17.5c.75 0 1.25-.4 1.25-1V9Zm-1 6H3V9h18v6Z"/><path d="M15 10h5v1h-5zM15 13h5v1h-5zM15 11.5h5v1h-5z"/>
        </svg>`,
    label: "顶部导航",
    category: "首页组件",
    select: true,
    content: { type: "navbar" },
  });
};
